<template>
  <tinymce :id="id" v-model="data" :other_options="config"></tinymce>
</template>

<script>
import tinymce from 'vue-tinymce-editor';
import zh_CN from '@/tinymce/zh_CN.js';
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 200
    },
  },
  components: {
    tinymce: tinymce
  },
  data() {
    return {
      data: this.value,
      id: 'tinymce' + Math.ceil(Math.random() * 100),
      config: {
        height: this.height+'px',
        language: 'zh_CN',
        convert_urls: false,
        // language_url: window.location.protocol + '//' + window.location.host + window.location.pathname + '/dist/tinymce/zh_CN.js',
        language_url: zh_CN,
        automatic_uploads: true,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample fontsizeselect fontselect', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
        images_upload_handler: (blobInfo, success, failure) => {
          // 图片异步上传处理函数
          var xhr, formData;

          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('post','/api/v2/upload/image', true);
          // xhr.open('POST', '/api/v2/upload/image/tinymce');
          xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));

          xhr.onload = function () {
            var json;

            if (xhr.status !== 200) {
              failure('HTTP Error: ' + xhr.status);
              return;
            }

            json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location !== 'string') {
              failure('Invalid JSON: ' + xhr.responseText);
              return;
            }
            success(json.location);
          };

          formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());

          xhr.send(formData);
        }
      }
    };
  },
  watch: {
    value(newVal, oldVal) {
      this.data = newVal;
    },
    data(newVal, oldVal) {
      this.$emit('input', newVal);
    }
  }
};
</script>
